package com.example.langchanin4jdemo1.controller;

import dev.langchain4j.agent.tool.*;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.service.tool.DefaultToolExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ToolDemo2 {
    static class WeatherUtil {
        @Tool("获取某一个具体城市的天气")
        public static String getWeather(@P("指定的城市") String city) {
            return "今天[ " + city + " ]天气晴朗";
        }
    }

    public static void main(String[] args) throws Exception {
        ChatLanguageModel model = QwenChatModel.builder()
                .apiKey("sk-875dd6ef14244431acdc7ccb974f5bfe")
                .modelName("qwen-max")
                .build();
        //构建工具集合，通过类构建
        List<ToolSpecification> toolSpecifications = ToolSpecifications.toolSpecificationsFrom(WeatherUtil.class);
        List<ChatMessage> chatMessages = new ArrayList<>();
        UserMessage userMessage = UserMessage.from("北京市今天的天气怎么样");
        chatMessages.add(userMessage);
        //第一次与AI大模型交互时，获得需要调用的工具类(将用户消息和工具列表传递给大模型)
        Response<AiMessage> aiMessageResponse = model.generate(chatMessages, toolSpecifications);

        AiMessage aiMessage = aiMessageResponse.content();

        // 需要执行的工具
        List<ToolExecutionRequest> toolExecutionRequests = aiMessage.toolExecutionRequests();
        chatMessages.add(aiMessage);

        WeatherUtil weatherUtil = new WeatherUtil();
        //将工具调用的方法与聊天消息一起传给AI大模型
        toolExecutionRequests.forEach(toolExecutionRequest -> {
            DefaultToolExecutor toolExecutor = new DefaultToolExecutor(weatherUtil,
                    toolExecutionRequest);
            String result = toolExecutor.execute(toolExecutionRequest,
                    UUID.randomUUID().toString());
            System.out.println("⼯具执⾏结果" + result);
            ToolExecutionResultMessage toolResultMessage =
                    ToolExecutionResultMessage.from(toolExecutionRequest, result);
            chatMessages.add(toolResultMessage);

        });

        //4、调⽤⼤模型，⽣成最终结果
        AiMessage finalResponse = model.generate(chatMessages).content();
        System.out.println("最终结果：" + finalResponse.text());

    }
}
